package com.hxd.otc.widget;

import android.text.Editable;
import android.text.TextWatcher;
import android.widget.EditText;

/**
 * 包  名 :  com.hxd.otc.widget
 * 类  名 :  LimitNumberTextWatcher
 * 作  者 :  卫广玉
 * 时  间 :  2018/6/15 14:41
 * 描  述 :  ${TODO}
 */
public class LimitNumberTextWatcher implements TextWatcher {

    protected EditText et;
    int integerLimit;
    int decimalLimit;

    public LimitNumberTextWatcher(EditText et) {
        super();
        this.et = et;
    }


    public LimitNumberTextWatcher(EditText et, int integerLimit, int decimalLimit) {
        super();
        this.et = et;
        this.integerLimit = integerLimit;
        this.decimalLimit = decimalLimit;
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {
    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before,
                              int count) {

        String str = s.toString().trim();

        //如果只有小数点，补全成0.
        if (str.equalsIgnoreCase(".")) {
            et.setText("0.");
            et.setSelection(et.getText().toString().length());
            return;
        }

        //限制不能输入加号
        if (str.contains("+")) {
            StringBuffer buf = new StringBuffer(str);
            int pos = str.indexOf("+");
            buf = buf.delete(pos, pos + 1);
            et.setText(buf.toString());
            et.setSelection(et.getSelectionEnd());
            return;
        }

        //下面是对位数的限制
        //前面如果有负号的话，给个偏移
        int offset = 0;
        String newStr = "";
        if (str.startsWith("-")) {
            offset = 1;
        } else {
        }
        //如果有小数点的话//判断小数点前后
        if (str.contains(".")) {
            int pos = str.indexOf(".");
            //前面多了//这种奇葩情况只有手动动了光标才会出现
            if (pos > (integerLimit + offset)) {
                StringBuffer buf = new StringBuffer(str);

                int cur = et.getSelectionEnd();
                if (cur > 0) {
                    buf = buf.delete(cur - 1, cur);

                    et.setText(buf.toString());
                    et.setSelection(cur - 1);
                }
            }

            //后面多了//把后面的截掉
            if (str.length() - 1 - pos > decimalLimit) {
                String ret = str.substring(0, pos + 1 + decimalLimit);
                et.setText(ret);
                et.setSelection(ret.length());
            }

        } else {//如果没有小数点的话，只判断小数点前面//不行，只取最前面的几位
            if (str.length() > (integerLimit + offset)) {
                String ret = str.substring(0, integerLimit + offset);
                et.setText(ret);
                et.setSelection(ret.length());
            }

        }

    }

    @Override
    public void afterTextChanged(Editable s) {
    }

}